<template>
  <div class="ele-body">
    <a-card border="false">
      <div>
        <div class="fs-16 fw-bolder margin-bottom-15">等级设置</div>
        <div class="flex align-center">
          <a-form-item label="开启赠送规则" style="width: 155px">
            <a-switch v-model:checked="is_open" @change="changeRule" />
          </a-form-item>
          <a-form-item
            label="礼金活动时间"
            class="margin-left-15"
            style="width: 155px"
          >
            <a-switch v-model:checked="cash_open" @change="changeCash" />
          </a-form-item>
          <a-form-item
            label=""
            :colon="false"
            class="margin-left-15"
            style="width: 300px"
            v-if="show"
          >
            <a-range-picker
              v-model:value="defaultPickerValue"
              :format="dateFormat"
              @calendarChange="daterangeUpdateValue"
            />
          </a-form-item>
          <a-form-item
            label=""
            :colon="false"
            class="margin-left-15 flex1"
            v-if="show"
          >
            <a-select
              show-search
              optionFilterProp="label"
              :options="options2"
              allow-clear
              placeholder="请选择"
              v-model:value="form.cash_type"
              @change="change1"
            />
          </a-form-item>
        </div>
      </div>
      <vxe-table
        ref="xTable"
        show-overflow="true"
        max-height="100%"
        :data="tableData"
      >
        <vxe-column field="level" title="货品小类" width="150">
          <template #default="{ row }">
            <div>{{ row.subclass_name }}</div>
          </template>
        </vxe-column>
        <vxe-column field="points_rule" title="赠送积分" width="700">
          <template #default="{ row }">
            <div
              class="flex align-center fs-12"
              style="white-space: nowrap"
              v-if="row.isEdit"
            >
              <div class="flex align-center">
                按
                <a-select
                  class="margin-x-10"
                  optionFilterProp="label"
                  :options="options1"
                  allow-clear
                  v-model:value="row.points_payed"
                  placeholder="请选择"
                  autocomplete="off"
                  style="width: 70px"
                />
                有效期
                <a-input
                  placeholder="请输入"
                  type="number"
                  class="margin-x-10"
                  style="width: 70px"
                  v-model:value="row.points_valid"
                />
                天
              </div>
              <div class="margin-left-15">
                <div
                  class="flex align-center margin-top-15"
                  v-for="(item, index) in row.points_rule"
                  :key="index"
                >
                  消费满
                  <a-input
                    placeholder="请输入"
                    type="number"
                    class="margin-x-10"
                    style="width: 70px"
                    v-model:value="item.sate_amount"
                  />
                  元,每
                  <a-input
                    placeholder="请输入"
                    type="number"
                    class="margin-x-10"
                    style="width: 70px"
                    v-model:value="item.each_amount"
                  />
                  元送
                  <a-input
                    placeholder="请输入"
                    type="number"
                    class="margin-x-10"
                    style="width: 70px"
                    v-model:value="item.points"
                  />
                  积分
                  <minus-circle-filled
                    class="margin-left-10 ele-text-danger"
                    @click="del(row.points_rule, index, 'points')"
                  />
                </div>
                <div
                  class="flex align-center fs-12 margin-left-15 margin-top-10 ele-text-primary"
                  @click="add(row, 'points')"
                >
                  <plus-circle-filled class="margin-right-10" />
                  添加规则（最多添加10个）
                </div>
              </div>
            </div>
            <div
              class="flex align-center fs-14"
              style="white-space: nowrap"
              v-else
            >
              <div class="flex align-center">
                按<span class="ele-text-primary">{{
                  row.points_payed_name || ''
                }}</span>
                有效期
                <span class="ele-text-primary">{{
                  row.points_valid || ''
                }}</span>
                天
              </div>
              <div class="margin-left-15">
                <div
                  class="flex align-center"
                  v-for="(item, index) in row.points_rule"
                  :key="index"
                >
                  消费满
                  <span class="ele-text-primary">{{
                    item.sate_amount || ''
                  }}</span>
                  元,每
                  <span class="ele-text-primary">{{
                    item.each_amount || ''
                  }}</span>
                  元送
                  <span class="ele-text-primary">{{ item.points || '' }}</span>
                  积分
                </div>
              </div>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="cash_rule" title="赠送礼金" width="700">
          <template #default="{ row }">
            <div
              class="flex align-center fs-12"
              style="white-space: nowrap"
              v-if="row.isEdit"
            >
              <div class="flex align-center">
                按
                <a-select
                  class="margin-x-10"
                  optionFilterProp="label"
                  :options="options1"
                  allow-clear
                  v-model:value="row.cash_payed"
                  placeholder="请选择"
                  autocomplete="off"
                  style="width: 70px"
                />
                有效期
                <a-input
                  placeholder="请输入"
                  type="number"
                  class="margin-x-10"
                  style="width: 70px"
                  v-model:value="row.cash_valid"
                />
                天
              </div>
              <div class="margin-left-15">
                <div
                  class="flex align-center margin-top-15"
                  v-for="(item, index) in row.cash_rule"
                  :key="index"
                >
                  消费满
                  <a-input
                    placeholder="请输入"
                    type="number"
                    class="margin-x-10"
                    style="width: 70px"
                    v-model:value="item.sate_amount"
                  />
                  元,每
                  <a-input
                    placeholder="请输入"
                    type="number"
                    class="margin-x-10"
                    style="width: 70px"
                    v-model:value="item.each_amount"
                  />
                  元送
                  <a-input
                    placeholder="请输入"
                    type="number"
                    class="margin-x-10"
                    style="width: 70px"
                    v-model:value="item.cash"
                  />
                  礼金
                  <minus-circle-filled
                    class="margin-left-10 ele-text-danger"
                    @click="del(row.cash_rule, index, 'cash')"
                  />
                </div>
                <div
                  class="flex align-center fs-12 margin-left-15 margin-top-10 ele-text-primary"
                  @click="add(row, 'cash')"
                >
                  <plus-circle-filled class="margin-right-10" />
                  添加规则（最多添加10个）
                </div>
              </div>
            </div>
            <div
              class="flex align-center fs-14"
              style="white-space: nowrap"
              v-else
            >
              <div class="flex align-center">
                按
                <span class="ele-text-primary">{{
                  row.cash_payed_name || ''
                }}</span>
                有效期
                <span class="ele-text-primary">{{ row.cash_valid || '' }}</span>
                天
              </div>
              <div class="margin-left-15">
                <div
                  class="flex align-center"
                  v-for="(item, index) in row.cash_rule"
                  :key="index"
                >
                  消费满
                  <span class="ele-text-primary">{{
                    item.sate_amount || ''
                  }}</span>
                  元,每
                  <span class="ele-text-primary">{{
                    item.each_amount || ''
                  }}</span>
                  元送
                  <span class="ele-text-primary">{{ item.cash || '' }}</span>
                  礼金
                </div>
              </div>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="points_discount_type" title="折扣限制" width="250">
          <template #default="{ row }">
            <div v-if="row.isEdit">
              <div class="flex align-center fs-12">
                积分：<a-radio-group
                  v-model:value="row.points_discount_type"
                  @change="changeLimit1"
                >
                  <a-radio value="0">不限制</a-radio>
                  <a-radio value="1">限制</a-radio>
                </a-radio-group>
              </div>
              <div
                class="flex align-center fs-12 margin-y-10"
                v-if="row.points_discount_type == 1"
              >
                <a-input
                  addon-before="销售折扣(大于等于)"
                  addon-after="%"
                  v-model:value="row.points_discount_min"
                />
              </div>
              <div class="flex align-center fs-12 margin-top-10">
                礼金：<a-radio-group
                  v-model:value="row.cash_discount_type"
                  @change="changeLimit2"
                >
                  <a-radio value="0">不限制</a-radio>
                  <a-radio value="1">限制</a-radio>
                </a-radio-group>
              </div>
              <div
                class="flex align-center fs-12 margin-y-10"
                v-if="row.cash_discount_type == 1"
              >
                <a-input
                  addon-before="销售折扣(大于等于)"
                  addon-after="%"
                  v-model:value="row.cash_discount_min"
                />
              </div>
            </div>
            <div v-else>
              <div class="flex align-center fs-14">
                积分：<span class="ele-text-primary">
                  <template v-if="row.points_discount_type == 1">限制</template>
                  <template v-if="row.points_discount_type == 0"
                    >不限制</template
                  > </span
                >,
                <div
                  class="flex align-center fs-12 margin-left-10"
                  v-if="row.points_discount_type == 1"
                >
                  销售折扣:<span class="ele-text-primary"
                    >大于等于 {{ row.points_discount_min || 0 }}%</span
                  >
                </div>
              </div>
              <div class="flex align-center fs-14 margin-top-10">
                礼金：<span class="ele-text-primary">
                  <template v-if="row.cash_discount_type == 1">限制</template>
                  <template v-if="row.cash_discount_type == 0"
                    >不限制</template
                  > </span
                >,
                <div
                  class="flex align-center fs-12 margin-left-10"
                  v-if="row.cash_discount_type == 1"
                >
                  销售折扣:<span class="ele-text-primary"
                    >大于等于{{ row.cash_discount_min || 0 }}%</span
                  >
                </div>
              </div>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="option" title="操作" width="150" fixed="right">
          <template #default="{ row }">
            <a-space>
              <a @click="edit(row)" v-if="!row.isEdit">编辑</a>
              <template v-else>
                <a @click="save(row)">保存</a>
                <a @click="row.isEdit = false">取消</a>
              </template>
            </a-space>
          </template>
        </vxe-column>
      </vxe-table>
    </a-card>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import moment from 'moment';
  import dayjs from 'dayjs';
  import { useRouter } from 'vue-router';
  import { actionFn } from '@/utils/action.js';
  import { daochuFn } from '@/utils/daochu.js';
  import {
    PlusOutlined,
    UploadOutlined,
    MinusCircleFilled,
    PlusCircleFilled,
    DownOutlined,
    ClearOutlined,
    RestOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import { get_setting, setting } from '@/api/member/points_send_rule';
  // 获取子组件
  const tableRef = ref(null);
  const router = useRouter();
  const { push } = useRouter();
  const options1 = ref([
    {
      label: '实收金额',
      value: 1
    },
    {
      label: '实售价',
      value: 2
    },
    {
      label: '原售价',
      value: 3
    }
  ]);
  const options2 = ref([
    {
      label: '只送礼金(在活动时间内只送礼金)',
      value: 1
    },
    {
      label: '送积分和礼金(在活动时间内， 既送积分，又送礼金)',
      value: 2
    },
    {
      label:
        '送积分/礼金,礼金优先(在活动时间内， 满足了送礼金的条件就送礼金，否则就送积分)',
      value: 3
    }
  ]);
  const is_open = ref(false);
  const cash_open = ref(false);
  const show = ref(false);
  const tableData = ref([]);
  const dateFormat = ref('YYYY-MM-DD');
  const getYMD = () => {
    let myDate = new Date();
    let myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
    let myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
    let myToday = myDate.getDate(); //获取当前日(1-31)
    myMonth = myMonth > 9 ? myMonth : '0' + myMonth;
    myToday = myToday > 9 ? myToday : '0' + myToday;
    let nowDate = myYear + '-' + myMonth + '-' + myToday;
    return nowDate;
  };
  const defaultPickerValue = ref([
    dayjs(getYMD(), dateFormat.value),
    dayjs(getYMD(), dateFormat.value)
  ]);

  const form = reactive({
    is_open: 1,
    cash_open: 1,
    cash_start_time: '',
    cash_end_time: '',
    cash_type: options2.value[0].value,
    subclass_code: '',
    points_payed: '',
    points_valid: '',
    points_rule: [
      {
        sate_amount: '',
        each_amount: '',
        points: ''
      }
    ],
    cash_payed: '',
    cash_valid: '',
    cash_rule: [
      {
        sate_amount: '',
        each_amount: '',
        cash: ''
      }
    ],
    points_discount_type: '',
    points_discount_min: '',
    cash_discount_type: '',
    cash_discount_min: ''
  });

  onMounted(() => {
    get_setting().then((res) => {
      is_open.value = res.send_conf.is_open ? true : false;
      form.is_open = res.send_conf.is_open;
      cash_open.value = res.send_conf.cash_open ? true : false;
      form.cash_open = res.send_conf.cash_open;
      form.cash_type = res.send_conf.cash_type;
      if (form.cash_open == 1) {
        show.value = true;
      }
      form.cash_start_time = res.send_conf.cash_start_time;
      form.cash_end_time = res.send_conf.cash_end_time;
      if (res.send_conf.cash_start_time && res.send_conf.cash_end_time) {
        defaultPickerValue.value = [
          dayjs(res.send_conf.cash_start_time, dateFormat.value),
          dayjs(res.send_conf.cash_end_time, dateFormat.value)
        ];
      }
      tableData.value = res.send_rule.data;
      tableData.value.forEach((item) => {
        item.isEdit = false;
        if (item.points_rule == null) {
          item.points_rule = [];
        }
        if (item.cash_rule == null) {
          item.cash_rule = [];
        }
        item.points_discount_type = item.points_discount_type.toString();
        item.cash_discount_type = item.cash_discount_type.toString();
      });
    });
  });

  const getCurrentData = () => {
    return new Date().toLocaleDateString();
  };

  const add = (row, type) => {
    if (type == 'points') {
      row.points_rule.push({
        sate_amount: '',
        each_amount: '',
        points: ''
      });
    }
    if (type == 'cash') {
      row.cash_rule.push({
        sate_amount: '',
        each_amount: '',
        cash: ''
      });
    }
  };
  const del = (arr, index, type) => {
    arr.splice(index, 1);
  };
  const save = (row) => {
    row.is_open = is_open.value ? 1 : 0;
    row.cash_open = cash_open.value ? 1 : 0;
    row.cash_start_time = form.cash_start_time;
    row.cash_end_time = form.cash_end_time;
    row.cash_type = form.cash_type;
    delete row.cash_rule['points'];
    console.log('===', row);
    setChange(row);
  };

  const edit = (row) => {
    row.isEdit = true;
  };
  const changeCash = (e) => {
    cash_open.value = e;
    if (e) {
      show.value = true;
    }
  };
  const changeRule = (e) => {
    is_open.value = e;
    let data = {
      is_open: is_open.value ? 1 : 0,
      cash_open: cash_open.value ? 1 : 0
    };
    setChange(data);
  };
  const change1 = (e, row) => {
    let data = {
      is_open: is_open.value ? 1 : 0,
      cash_open: cash_open.value ? 1 : 0,
      cash_start_time: form.cash_start_time,
      cash_end_time: form.cash_end_time,
      cash_type: form.cash_type
    };
    setChange(data);
  };
  const change2 = (e, row) => {
    console.log(e, row);
  };
  const changeLimit1 = (e) => {
    console.log(e);
  };
  const changeLimit2 = (e) => {
    console.log(e);
  };
  const daterangeUpdateValue = (date, dateString) => {
    if (dateString[0] && dateString[1]) {
      form.cash_start_time = dateString[0];
      form.cash_end_time = dateString[1];
      defaultPickerValue.value = dateString;
      let data = {
        is_open: is_open.value ? 1 : 0,
        cash_open: cash_open.value ? 1 : 0,
        cash_start_time: form.cash_start_time,
        cash_end_time: form.cash_end_time,
        cash_type: form.cash_type
      };
      setChange(data);
    }
  };
  const setChange = (data) => {
    setting(data)
      .then((res) => {
        data.isEdit = false;
        message.success(res.msg);
      })
      .catch((e) => {
        message.error(e.message);
      });
  };
</script>

<style lang="less" scoped>
  :deep(.vxe-table--render-default.border--default .vxe-body--column) {
    background-image: none;
  }

  :deep(.vxe-table--body-wrapper.fixed-right--wrapper) {
    bottom: 0 !important;
  }

  :deep(.vxe-table--body) {
    height: 100%;
  }
</style>
